using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;

namespace Wechat.Service.Extractor;

public class ExtractorService : IExtractorService
{
    public async Task<string> ExtractContentFromHtmlByPathAsync(string path)
    {
        // 使用File.ReadAllText方法读取整个HTML文件的内容
        string htmlContent = File.ReadAllText(path);
        // 创建HTML解析器
        var parser = new HtmlParser();
        // 解析HTML内容
        var document = await parser.ParseDocumentAsync(htmlContent);
        // 查找id为"name"的h1元素
        var contentEle = document.QuerySelector("#js_content");
        var content = contentEle?.TextContent.ToString() ?? "";
        return content;
    }

    public async Task<string> ExtractTitleFromHtmlByPathAsync(string path)
    {
        // 使用File.ReadAllText方法读取整个HTML文件的内容
        string htmlContent = File.ReadAllText(path);
        // 创建HTML解析器
        var parser = new HtmlParser();
        // 解析HTML内容
        var document = await parser.ParseDocumentAsync(htmlContent);
        // 查找id为"name"的h1元素
        var titleEle = document.QuerySelector("#activity-name");
        var title = titleEle?.TextContent.ToString() ?? string.Empty;
        return SanitizeFileName(title);
    }

    public static string SanitizeFileName(string fileName)
    {
        string invalidChars = System.Text.RegularExpressions.Regex.Escape(
            new string(System.IO.Path.GetInvalidFileNameChars())
        );
        string invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);

        return System.Text.RegularExpressions.Regex.Replace(fileName, invalidRegStr, "_");
    }

    public List<string> ExtractLinksFromHtml(string html)
    {
        var urls = new List<string>();
        // 定义超链接的正则表达式
        string hyperlinkPattern = @"(http|https)://[^\s]*";
        // 创建Regex对象
        Regex regex = new Regex(hyperlinkPattern);
        // 查找所有匹配的超链接
        MatchCollection matches = regex.Matches(html);
        // System.Console.WriteLine(matches.Count);
        foreach (Match match in matches)
        {
            // System.Console.WriteLine(match.Value.Count());
            // System.Console.WriteLine(match.Value);
            if (match.Value.Count() < 200 || match.Value.Count() > 300)
                continue;
            string url = new string(match.Value.Take(match.Value.Length - 26).ToArray());
            // System.Console.WriteLine(url);
            // System.Console.WriteLine(match.Value.Count());
            // System.Console.WriteLine(url);

            Uri myUri = new(url.Replace("&amp;", "&"));
            NameValueCollection originalQueryCollection = HttpUtility.ParseQueryString(myUri.Query);
            string? biz = originalQueryCollection.Get("__biz");
            string? mid = originalQueryCollection.Get("mid");
            string? idx = originalQueryCollection.Get("idx");
            string? sn = originalQueryCollection.Get("sn");
            if (
                string.IsNullOrEmpty(biz)
                || string.IsNullOrEmpty(mid)
                || string.IsNullOrEmpty(idx)
                || string.IsNullOrEmpty(sn)
            )
                continue;

            // 创建一个空的查询字符串实例
            NameValueCollection newQueryCollection = HttpUtility.ParseQueryString(string.Empty);
            // 添加参数
            newQueryCollection.Add("__biz", biz);
            newQueryCollection.Add("mid", mid);
            newQueryCollection.Add("idx", idx);
            newQueryCollection.Add("sn", sn);
            // 将查询字符串转换为字符串形式
            string? query = newQueryCollection.ToString();
            if (string.IsNullOrEmpty(query))
                continue;
            // Console.WriteLine($"https://mp.weixin.qq.com/s?{query}");
            var newUrl = $"https://mp.weixin.qq.com/s?{query}";

            // System.Console.WriteLine(urls.Exists(url => url == newUrl));
            if (urls.Exists(url => url == newUrl))
                continue;
            urls.Add(newUrl);

            // System.Console.WriteLine(biz);
            // System.Console.WriteLine(mid);
            // System.Console.WriteLine(idx);
            // System.Console.WriteLine(sn);
            // throw new Exception("============================================================");
        }
        var distinctUrls = urls.GroupBy(url => url.Length > 150 ? url.Substring(0, 150) : url) // 根据前180位分组
            .Select(group => group.OrderByDescending(u => u.Length).First()) // 选择每个分组的第一个元素
            .ToList(); // 转换为List
        // System.Console.WriteLine(distinctUrls.Count);
        // foreach(var distinctUrl in distinctUrls){
        //     System.Console.WriteLine(distinctUrl);
        //     System.Console.WriteLine(distinctUrl.Count());
        // }
        return distinctUrls;
    }

    public async Task<List<string>> ExtractLinksFromTopicHtmlAsync(string html)
    {
        var document = await new HtmlParser().ParseDocumentAsync(html);
        var scriptElements = document.QuerySelectorAll("script");
        var content = string.Empty;
        // 定义超链接的正则表达式
        string hyperlinkPattern = @"(http|https)://[^\s]*";
        // 创建Regex对象
        Regex regex = new Regex(hyperlinkPattern);
        foreach (var script in scriptElements)
        {
            // 检查<span>元素的style属性
            if (script.TextContent.Contains("window.cgiData"))
            {
                content = script.TextContent;
                break;
            }
        }
        var urls = new List<string>();
        // 查找所有匹配的超链接
        MatchCollection matches = regex.Matches(content);
        // System.Console.WriteLine(matches.Count);
        foreach (Match match in matches)
        {
            // System.Console.WriteLine(match.Value.Count());
            // System.Console.WriteLine(match.Value);
            // Console.WriteLine(match.Value.Count());
            if (match.Value.Count() < 200 || match.Value.Count() > 300)
                continue;

            string url = new string(match.Value.Take(match.Value.Length - 26).ToArray());
            // System.Console.WriteLine(url);
            Uri myUri = new(url.Replace("&amp;amp;", "&").Replace("&amp;", "&"));
            NameValueCollection originalQueryCollection = HttpUtility.ParseQueryString(myUri.Query);
            string? biz = originalQueryCollection.Get("__biz");
            string? mid = originalQueryCollection.Get("mid");
            string? idx = originalQueryCollection.Get("idx");
            string? sn = originalQueryCollection.Get("sn");
            // System.Console.WriteLine(url.Replace("&amp;amp;", "&").Replace("&amp;","&"));
            // System.Console.WriteLine($"biz = {biz}, mid= {mid}, idx={idx}, sn = {sn}");
            if (
                string.IsNullOrEmpty(biz)
                || string.IsNullOrEmpty(mid)
                || string.IsNullOrEmpty(idx)
                || string.IsNullOrEmpty(sn)
            )
                continue;

            // 创建一个空的查询字符串实例
            NameValueCollection newQueryCollection = HttpUtility.ParseQueryString(string.Empty);
            // 添加参数
            newQueryCollection.Add("__biz", biz);
            newQueryCollection.Add("mid", mid);
            newQueryCollection.Add("idx", idx);
            newQueryCollection.Add("sn", sn);
            // 将查询字符串转换为字符串形式
            string? query = newQueryCollection.ToString();
            if (string.IsNullOrEmpty(query))
                continue;
            // Console.WriteLine($"https://mp.weixin.qq.com/s?{query}");
            var newUrl = $"https://mp.weixin.qq.com/s?{query}";
            // Console.WriteLine(newUrl);
            // System.Console.WriteLine(urls.Exists(url => url == newUrl));
            if (urls.Exists(url => url == newUrl))
                continue;
            urls.Add(newUrl);
            // System.Console.WriteLine(urls);
        }
        return urls;
    }
}
